package com.heima.user.service.impl;

import com.alibaba.nacos.client.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
//@Transactional(rollbackFor = Exception.class)
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {


    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {


        //1. 参数检查

        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "参数异常");
        }

        //2. 条件查询

        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> queryWrapper = new LambdaQueryWrapper<>();

        if (dto.getStatus() != null) {
            queryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> iPage = page(page, queryWrapper);

        //3. 返回结果
        return new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());
    }

    @Override
    public ResponseResult authFail(AuthDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "参数错误");
        }

        //2.赋值status

        Short status = AdminConstants.FAIL_AUTH;

        //3.调用更新方法

        return this.updateStatusById(dto, status);
    }

    @Override
    public ResponseResult authPass(AuthDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "参数错误");
        }

        //2.赋值status

        Short status = AdminConstants.PASS_AUTH;

        //3.调用更新方法

        return this.updateStatusById(dto, status);
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult updateStatusById(AuthDto dto, Short status) {

        // 1.检查参数
        if (dto == null || status == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "参数错误");
        }
        // 2.查询用户是否存在
        ApUserRealname userRealname = getById(dto.getId());

        if (userRealname == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "不存在不存在！");
        }
        if (userRealname.getStatus() != AdminConstants.WAIT_AUTH) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "该用户已经认证过了");
        }
        // 3.赋值status 并判断
        userRealname.setStatus(status);
        userRealname.setUpdatedTime(new Date());
        if(StringUtils.isNotBlank(dto.getMsg())){
            userRealname.setReason(dto.getMsg());
        }

        updateById(userRealname);
        Integer userId = userRealname.getUserId();

        ApUser apUser = this.apUserMapper.selectById(userId);
        if (apUser==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "此人已投海");
        }

        if (status.equals(AdminConstants.PASS_AUTH)) {
            // 3.1  通过则 新建自媒体信息，作者信息

            ResponseResult wmUserResult = createWmUser(apUser);
            WmUser wmUser = (WmUser) wmUserResult.getData();
            ResponseResult apAuthorResult = createApAuthor(wmUser);

//            WmUser wmUser = new WmUser();
//
//            wmUser.setApUserId(apUser.getId());
//
//            wmUser.setName(apUser.getName());
//
//            wmUser.setPassword(apUser.getPassword());
//
//            wmUser.setSalt(apUser.getSalt());
//
//            wmUser.setImage(apUser.getImage());
//
//            wmUser.setPhone(apUser.getPhone());
//
//            wmUser.setCreatedTime(new Date());
//
//            ApAuthor author = new ApAuthor();
//
//            author.setName(apUser.getName());
//
//            author.setUserId(apUser.getId());
//
//            author.setCreatedTime(new Date());
//
//
//            wemediaFeign.insert(wmUser);
//            articleFeign.insert(author);

//            ApAuthor author1 = articleFeign.findByUserId(apUser.getId()).getData();
//            WmUser wmUser1 = wemediaFeign.findByName(apUser.getName()).getData();
//
//            author1.setWmUserId(wmUser1.getId());
//            wmUser.setApAuthorId(author1.getId());
//            wemediaFeign.insert(wmUser);
//            articleFeign.insert(author);

        }
        // 3.2  未通过则随便写个理由直接遣返
        apUser.setFlag((short) 1);
        apUserMapper.updateById(apUser);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    private ResponseResult createApAuthor(WmUser wmUser) {
        //1 检查是否成功调用
        ResponseResult<ApAuthor> apAuthorResult = articleFeign.findByUserId(wmUser.getApUserId());
        if(apAuthorResult.getCode().intValue() != 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"调用失败");
        }
        //2. 检查作者信息是否已经存在
        ApAuthor apAuthor = apAuthorResult.getData();
        if (apAuthor != null) {
            return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"作者信息已存在");
        }
        //3. 添加作者信息
        apAuthor = new ApAuthor();
        apAuthor.setCreatedTime(new Date());
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2); // 自媒体人类型
        apAuthor.setUserId(wmUser.getApUserId()); // APP 用户ID
        apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID
        ResponseResult result = articleFeign.insert(apAuthor);
        //4. 结果失败，抛出异常
        if (result.getCode() != 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "创建作者账户失败");
        }
        return result;
    }
    /**
     * 4.1 创建自媒体账户
     * @param apUser  APP端用户
     * @return
     */
    private ResponseResult createWmUser(ApUser apUser) {
        //1 查询自媒体账号是否存在（APP端用户密码和自媒体密码一致）
        ResponseResult<WmUser> wmUserResult = wemediaFeign.findByName(apUser.getName());
        if(wmUserResult.getCode().intValue() != 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"调用失败");
        }
        WmUser wmUser =wmUserResult.getData();
        if (wmUser != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"自媒体用户信息已存在");
        }
        wmUser = new WmUser();
        wmUser.setName(apUser.getName());
        wmUser.setSalt(apUser.getSalt());  // 盐
        wmUser.setPassword(apUser.getPassword()); // 密码
        wmUser.setPhone(apUser.getPhone());
        wmUser.setCreatedTime(new Date());
        wmUser.setType(0); // 个人
        wmUser.setApUserId(apUser.getId());  // app端用户id
        wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());

        ResponseResult<WmUser> saveResult = wemediaFeign.insert(wmUser);
        if(saveResult.getCode().intValue()!=0){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,saveResult.getErrorMessage());
        }
        return saveResult;
    }

}
